package com.smr.micservice.diablomovie.service.impl;

import com.smr.micservice.diablomovie.common.pojo.po.User;
import com.smr.micservice.diablomovie.service.define.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserService {

    private static final ConcurrentHashMap<Long, User> USER_MAP = new ConcurrentHashMap<>();


    @Cacheable(value = "users",key = "#userId")
    @Override
    public User getUser(Long userId) {
        if (USER_MAP.isEmpty()) {
            User user1 = new User();
            user1.setUserId(1L);
            user1.setCreateDate(new Date());
            user1.setUsername("wangmazio");
            user1.setPassword("123456");

            User user2 = new User();
            user2.setUserId(2L);
            user2.setCreateDate(new Date());
            user2.setUsername("zhangsan");
            user2.setPassword("lisi");
            USER_MAP.put(user1.getUserId(), user1);
            USER_MAP.put(user2.getUserId(), user2);

        }
        return USER_MAP.get(userId);
    }

    @CacheEvict(value = "users", key = "'users_'+#user.userId")
    @Override
    public void updateUser(User user) {
        User orgin = USER_MAP.get(user.getUserId());
        if (orgin == null) {
            return;
        }
        orgin.setUsername(user.getUsername());
        orgin.setPassword(user.getPassword());
        orgin.setCreateDate(new Date());
    }

}
